import { Router } from 'express'
import { schemaService } from '../services/schemaService'
import { logger } from '../utils/logger'
import { ApiResponse } from '../types/api'

const router = Router()

/**
 * 获取数据库schema信息
 */
router.get('/connections/:connectionId/schema', async (req, res) => {
  try {
    const { connectionId } = req.params
    const { refresh } = req.query
    
    const schemaInfo = await schemaService.getSchemaInfo(
      connectionId,
      refresh === 'true'
    )
    
    const response: ApiResponse = {
      success: true,
      data: schemaInfo,
      message: 'Schema information retrieved successfully',
    }
    
    res.json(response)
  } catch (error) {
    logger.error('Failed to get schema info:', error)
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'SCHEMA_FETCH_ERROR',
        message: error instanceof Error ? error.message : 'Failed to fetch schema information',
      },
    }
    res.status(500).json(response)
  }
})

/**
 * 搜索表名
 */
router.get('/connections/:connectionId/schema/tables/search', async (req, res) => {
  try {
    const { connectionId } = req.params
    const { keyword } = req.query
    
    if (!keyword || typeof keyword !== 'string') {
      const response: ApiResponse = {
        success: false,
        error: {
          code: 'INVALID_PARAMETER',
          message: 'Keyword parameter is required',
        },
      }
      return res.status(400).json(response)
    }
    
    const tables = await schemaService.searchTables(connectionId, keyword)
    
    const response: ApiResponse = {
      success: true,
      data: tables,
      message: 'Tables searched successfully',
    }
    
    res.json(response)
  } catch (error) {
    logger.error('Failed to search tables:', error)
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'TABLE_SEARCH_ERROR',
        message: error instanceof Error ? error.message : 'Failed to search tables',
      },
    }
    res.status(500).json(response)
  }
})

/**
 * 搜索列名
 */
router.get('/connections/:connectionId/schema/columns/search', async (req, res) => {
  try {
    const { connectionId } = req.params
    const { keyword, table } = req.query
    
    if (!keyword || typeof keyword !== 'string') {
      const response: ApiResponse = {
        success: false,
        error: {
          code: 'INVALID_PARAMETER',
          message: 'Keyword parameter is required',
        },
      }
      return res.status(400).json(response)
    }
    
    const columns = await schemaService.searchColumns(
      connectionId,
      keyword,
      table as string
    )
    
    const response: ApiResponse = {
      success: true,
      data: columns,
      message: 'Columns searched successfully',
    }
    
    res.json(response)
  } catch (error) {
    logger.error('Failed to search columns:', error)
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'COLUMN_SEARCH_ERROR',
        message: error instanceof Error ? error.message : 'Failed to search columns',
      },
    }
    res.status(500).json(response)
  }
})

/**
 * 获取表的列信息
 */
router.get('/connections/:connectionId/schema/tables/:tableName/columns', async (req, res) => {
  try {
    const { connectionId, tableName } = req.params
    
    const columns = await schemaService.getTableColumns(connectionId, tableName)
    
    const response: ApiResponse = {
      success: true,
      data: columns,
      message: 'Table columns retrieved successfully',
    }
    
    res.json(response)
  } catch (error) {
    logger.error('Failed to get table columns:', error)
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'TABLE_COLUMNS_ERROR',
        message: error instanceof Error ? error.message : 'Failed to get table columns',
      },
    }
    res.status(500).json(response)
  }
})

/**
 * 获取自动补全建议
 */
router.post('/connections/:connectionId/schema/autocomplete', async (req, res) => {
  try {
    const { connectionId } = req.params
    const { currentWord, previousWords, position } = req.body
    
    if (!currentWord || !Array.isArray(previousWords) || !position) {
      const response: ApiResponse = {
        success: false,
        error: {
          code: 'INVALID_PARAMETER',
          message: 'currentWord, previousWords, and position are required',
        },
      }
      return res.status(400).json(response)
    }
    
    const suggestions = await schemaService.getAutoCompleteSuggestions(
      connectionId,
      { currentWord, previousWords, position }
    )
    
    const response: ApiResponse = {
      success: true,
      data: suggestions,
      message: 'Autocomplete suggestions retrieved successfully',
    }
    
    res.json(response)
  } catch (error) {
    logger.error('Failed to get autocomplete suggestions:', error)
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'AUTOCOMPLETE_ERROR',
        message: error instanceof Error ? error.message : 'Failed to get autocomplete suggestions',
      },
    }
    res.status(500).json(response)
  }
})

/**
 * 刷新schema缓存
 */
router.post('/connections/:connectionId/schema/refresh', async (req, res) => {
  try {
    const { connectionId } = req.params
    
    const schemaInfo = await schemaService.refreshSchema(connectionId)
    
    const response: ApiResponse = {
      success: true,
      data: schemaInfo,
      message: 'Schema cache refreshed successfully',
    }
    
    res.json(response)
  } catch (error) {
    logger.error('Failed to refresh schema cache:', error)
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'SCHEMA_REFRESH_ERROR',
        message: error instanceof Error ? error.message : 'Failed to refresh schema cache',
      },
    }
    res.status(500).json(response)
  }
})

/**
 * 清除所有schema缓存
 */
router.delete('/schema/cache', async (req, res) => {
  try {
    await schemaService.clearAllCache()
    
    const response: ApiResponse = {
      success: true,
      message: 'All schema cache cleared successfully',
    }
    
    res.json(response)
  } catch (error) {
    logger.error('Failed to clear schema cache:', error)
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'CACHE_CLEAR_ERROR',
        message: error instanceof Error ? error.message : 'Failed to clear schema cache',
      },
    }
    res.status(500).json(response)
  }
})

export default router